/*
** 3505.c
** 
** Made by (seakage2h)
** Login   <seakage2h@seakage2h-ubuntu>
** 
** Started on  Sat Sep  6 17:11:33 2008 seakage2h
** Last update Sun May 12 01:17:25 2002 Speed Blue
*/

/* #include "3505.h" */
#include <stdio.h>
#include <stdlib.h>

#define myabs(x) (((x)>=0)?(x):-(x))

/* /\* DEPRECATED: useless *\/ */
/* typedef struct  */
/* { */
/*      int *car_slots; */
     
/* } car_ring; */

int main()
{
     int instance, h, rl;	/* h:height, rl:convey ring length */
     int *park_slots, *ring_pos;
     int i, j;
     int slot_order;
     int time;
     div_t tmp;
     int target_floor, target_pos, convey_turns;
               

     scanf("%d", &instance);

     /* A big loop */
     for(i = 0; i < instance; i++){
	  time = 0;
	  scanf("%d%d", &h, &rl);

	  /* store the occupied slots, corresponding to each ordered car
	   * initially all are -1(no car) */
	  park_slots = (int*)malloc(sizeof(int) * (h * rl + 1));
	  for(j = 0; j <= h * rl; j++) park_slots[j] = -1;
	  /* store the position of the conveyor ring of each floor
	   * initially all at 0 */
	  ring_pos = (int*)calloc(h, sizeof(int));
	  
	  for(j = 0; j < h * rl; j++){
	       scanf("%d", &slot_order);
	       if (slot_order != -1)
		    park_slots[slot_order - 1] = j;
	  }

/* 	  /\* DEBUG: print the parked car slots *\/ */
/* 	  for(j = 0; park_slots[j] != -1; j++) */
/* 	       printf("The No.%d car parked at slot %d\n", */
/* 		      j+1, park_slots[j] + 1); */
	       
	  /* SIMULATE: the serve process */
	  for(j = 0; park_slots[j] != -1; j++){
	       tmp = div(park_slots[j], rl);
	       target_floor = tmp.quot;
	       target_pos = tmp.rem;
	       
	       /* wish the compiler can optimize the recomputation for us */
	       convey_turns =						\
		    (myabs(ring_pos[target_floor] - target_pos) >	\
		     rl - myabs(ring_pos[target_floor] - target_pos))?	\
		    (rl - myabs(ring_pos[target_floor] - target_pos)):	\
		    myabs(ring_pos[target_floor] - target_pos);
	       
/* 	       /\* DEBUG: test the convey_turns *\/ */
/* 	       printf("Need to turn %d\n", convey_turns); */
	       
	       ring_pos[target_floor] = target_pos;
			  
	       /* CALCULATE: the single step serve time */
	       time += (target_floor * 10 * 2 + convey_turns * 5);
	  }

	  printf("%d\n", time);
     }

     return 0;
}

     /* calculate the smallest turn to the target car in either direction */
     
     /* store each car position in a whole array, make it easy to find
      * its location(which floor, which slot) */

     /* go through the fetching car process, calculate the time */
